/**
 * Created by zy on 2016/7/7.
 * 详情 - 缺陷维修管理 - 管体缺陷
 */


;(function ($, window, document, undefined) {

    /**
     * gis地图参数
     */
    var gisJsonArr = [
        {
            'typeName': 'pipeLineId',
            'gisIdArray': []
        },
        {
            'typeName': 'inspDefect',
            'gisIdArray': []
        },
        {
            'typeName': 'valveRoomPoint',
            'gisIdArray': []
        }
    ];

    /**
     * dyMap 地图对象, currentMap 当前地图对象
     */
    var dyMapIfarme = $('#JQ_dyMap'), dyMap, curent_map;

    // 项目名称
    var $project_name = $('#JQ_project_name');

    // 查询对象
    var filter = {
        getSearch: function (param) {
            var data = {};
            data.mode = true;
            data.repairTaskId = function () {
                return $('#JQ_repair_id').val();
            }();
            if (param) {
                if (param.start == 0) {
                    data['jsonBean.pageNum'] = 1;
                } else {
                    data['jsonBean.pageNum'] = param.start / 10 + 1;
                }
                data['jsonBean.pageCount'] = param.length;
            }
            return data;
        }
    };

    // 初始化表格数据
    var $table_01 = $('#JQ_datatable_01');
    var DT01 = $table_01.DataTable({
        'language': {
            'paginate': {
                'next': '下一页',
                'previous': '上一页'
            },
            'info': '本次检索共 _TOTAL_ 条，每页显示 10 条，共 _PAGES_ 页',
            'zeroRecords': DyyBase.defect_empty(),
            'infoEmpty': ''
        },
        'autoWidth': false,
        'serverSide': true,
        'pageLength': 10,
        'ordering': false,
        'processing': false,
        'searching': false,
        'lengthChange': false,
        'ajax': function (data, callback) {
            var param = filter.getSearch(data);
            DyyBase.ajax(defectApi.url_repair_details(), param, function (dataset) {

                // 封装返回数据
                var returnData = {};
                returnData.draw = data.draw;
                returnData.recordsTotal = dataset.result.defectInfoList.total;
                returnData.recordsFiltered = dataset.result.defectInfoList.total;
                returnData.data = DyyBase.clearNull(dataset.result.defectInfoList.list);

                // 项目名称
                $project_name.text(dataset.result.repairTask.name);
                // 管道中心线 gisid
                $('#JQ_pipeGisId').val(dataset.result.pipeLineCenterLine.gisId);
                // 场站阀室gisid
                gisJsonArr[2].gisIdArray = dataset.result.valveRoomGisIds;

                // 回调渲染
                callback(returnData);
            });
        },
        'drawCallback': function () {
        },
        'columns': [
            {
                data: 'pipeName', render: function (data, type, row) {
                return '<span title="' + data + '">' + data + '</span><input type="hidden" name="gisid" value="' + row.gisId + '">';
            }
            },
            {
                data: 'mileage', render: function (data) {
                return '<span title="' + data + '">' + data + '</span>';
            }
            },
            {
                data: 'length', render: function (data, type, row) {
                return '<span title="' + data + '/' + row.width + '/' + row.depth + '">' + data + '/' + row.width + '/' + row.depth + '</span>'
            }
            },
            {
                data: 'clock', render: function (data) {
                return '<span title="' + data + '">' + data + '</span>';
            }
            },
            {
                data: 'erf', render: function (data) {
                return '<span title="' + data + '">' + data + '</span>';
            }
            },
            {
                data: 'repairSuggestion', render: function (data) {
                return '<span title="' + data + '">' + data + '</span>';
            }
            },
            {
                data: 'planRepairTime', render: function (data) {
                return '<span title="' + Dyy.getDate(data) + '">' + Dyy.getDate(data) + '</span>';
            }
            },
            {
                data: 'repairState_label', render: function (data) {
                switch (data){
                    case '待修复':
                        return '<span class="zy-status-blue" title="' + data + '">' + data + '</span>';
                        break;
                    case '修复中':
                        return '<span class="zy-status-blue" title="' + data + '">' + data + '</span>';
                        break;
                    case '已修复':
                        return '<span class="zy-status-gray" title="' + data + '">' + data + '</span>';
                        break;
                    case '难以修复':
                        return '<span class="zy-status-red" title="' + data + '">' + data + '</span>';
                        break;
                    case '待换管':
                        return '<span class="zy-status-gray" title="' + data + '">' + data + '</span>';
                        break;
                    default:
                        return '<span class="zy-status-gray" title="未知">未知</span>';
                        break;
                }
            }
            },
            {
                data: 'defectId', render: function (data) {
                var task = DyyBase.unicodeUrl($project_name.text());
                var url = defectApi.url_repair_map() + '?defectInfoId=' + data + '&projectName=' + task;
                return '<a href="' + url + '"><i data-a="' + data + '" class="zy-record-map-icon" title="地图"></i></a>';
            }
            },
            {
                data: 'defectId', render: function (data, type, row) {
                return '<i data-defectId="' + data + '" data-status="' + row.repairState + '" data-code="' + row.customNumber + '" data-pipe="' + row.pipeName + '" class="zy-record-icon" title="维修记录"></i>';
            }
            },
            {
                data: 'defectId', render: function (data) {
                return '<i data-defectId="' + data + '" class="zy-details-icon" title="详情"></i>';
            }
            }
        ]
    });

    // 展开详情
    $table_01.delegate('i.zy-details-icon', 'click', function () {
        // 当前按钮
        var $this_i = $(this);
        // 携带的ID
        var defectId = $this_i.attr('data-defectId');
        // 当前父级 tr
        var $tr = $this_i.parent('td').parent('tr');
        // 当前父级 tbody
        var $tbody = $this_i.parent('td').parent('tr').parent('tbody');
        // 已经存在的动态 tr ?
        var $dy_tr = $tbody.find('tr[data-defectId-details="' + defectId + '"]');

        // 激活当前按钮选中样式
        $table_01.find('i.zy-record-icon').removeClass('active');
        $table_01.find('i.zy-details-icon').removeClass('active');
        $this_i.addClass('active');

        // 隐藏其他动态行
        $table_01.find('tr.zy-dy-tr').hide();

        // 有则显示 无则填充
        if ($dy_tr.length > 0) {
            $dy_tr.show();
        } else {
            fillAdviseDetails($tr, defectId);
        }
    });

    // 收起详情
    $table_01.delegate('button.zy-pick-up', 'click', function () {
        var $this_btn = $(this);
        var defectId = $this_btn.attr('data-defectId');
        $table_01.find('tr[data-defectId-details="' + defectId + '"]').hide();
        $table_01.find('i.zy-details-icon').removeClass('active');
    });

    //xyf edit 2012-12-22
    $table_01.delegate('span.xyf-null', 'click', function () {
        $table_01.MSG({content:'该条项目没有图片数据！'});
    });


    // 填充详情
    function fillAdviseDetails(tr, id) {
        var data_row = DT01.row(tr).data(); // 行数据
        var $dy_tr = $('<tr class="zy-dy-tr" data-defectId-details="' + id + '"><td colspan="11"><div class="zy-details-box"></div></td></tr>');
        var $dy_box = $dy_tr.find('div.zy-details-box');
        var imglist = data_row.attachmentList, imgs = '';
        var imghead = '<p class="zy-dy-p-head">现场照片：</p>';
        if (imglist.length > 0) {

            var imgbody = '';
            for (var i = 0, len = imglist.length; i < len; i++) {
                imgbody += '<span><a href="' + DyyBase.file_path + imglist[i]['path'] + '" target="_blank"><img class="list" src="' + DyyBase.file_path + imglist[i]['path'] + '"></a></span>';
            }
            if (imgbody) {
                imgbody = '<p class="zy-imglist">' + imgbody + '</p>';
                imgs = imghead + imgbody;
            }
        }else{
            //xyf edit 2012-12-22
            var imgEmpty = '<span class="xyf-null"></span>';
            if (imgEmpty) {
                imgEmpty = '<div class="zy-imglist" style="height: 80px;">' + imgEmpty + '</div>';
                imgs = imghead + imgEmpty;
            }

        }
        var html = '<div class="zy-dy-inner"><div class="zy-dy-p">'
            + '<p title="缺陷编号：'+data_row.customNumber+'">缺陷编号：' + data_row.customNumber + '</p>'
            + '<p title="缺陷类型：'+data_row.featureSubType+'">缺陷类型：' + data_row.featureSubType + '</p>'
            + '<p title="管道名称：'+data_row.pipeName+'">管道名称：' + data_row.pipeName + '</p>'
            + '<p title="绝对距离(m)：'+data_row.mileage+'">绝对距离(m)：' + data_row.mileage + '</p>'
            + '<p title="长/宽/深(mm)：'+data_row.length + '/' + data_row.width + '/' + data_row.depth+'">长/宽/深(mm)：' + data_row.length + '/' + data_row.width + '/' + data_row.depth + '</p>'
            + '<p title="时钟位置(h:min)：'+data_row.clock+'">时钟位置(h:min)：' + data_row.clock + '</p>'
            + '<p title="ERF：'+data_row.erf+'">ERF：' + data_row.erf + '</p>'
            + '<p title="维修建议：'+data_row.repairSuggestion+'">维修建议：' + data_row.repairSuggestion + '</p>'
            + '<p title="建议维修方法：'+data_row.planRepairType+'">建议维修方法：' + data_row.planRepairType + '</p>'
            + '<p title="修复状态：'+data_row.repairState_label+'">修复状态：' + data_row.repairState_label + '</p>'
            + '<p title="最迟维修时间：'+Dyy.getDate(data_row.planRepairTime)+'">最迟维修时间：' + Dyy.getDate(data_row.planRepairTime) + '</p>' + imgs + '</div>'
            + '<div class="zy-dy-footer"><button data-defectId="' + id + '" class="zy-button zy-pick-up" type="button"><i></i>收起</button></div></div>';
        // 内部装入 html
        $dy_box.html(html);
        // 后方插入 tr
        tr.after($dy_tr);
    }

    // 展开维修记录
    $table_01.delegate('i.zy-record-icon', 'click', function () {
        // 当前按钮
        var $this_i = $(this);
        // 维修状态
        var status = $this_i.attr('data-status');
        // 携带的ID
        var defectId = $this_i.attr('data-defectId');
        // 任务编号
        var data_code = $this_i.attr('data-code');
        // 管道名称
        var data_pipe = $this_i.attr('data-pipe');
        // 当前父级 tr
        var $tr = $this_i.parent('td').parent('tr');
        // 当前父级 tbody
        var $tbody = $this_i.parent('td').parent('tr').parent('tbody');
        // 已经存在的动态 tr ?
        var $dy_tr = $tbody.find('tr[data-defectId-repair="' + defectId + '"]');

        // 激活当前按钮选中样式
        $table_01.find('i.zy-record-icon').removeClass('active');
        $table_01.find('i.zy-details-icon').removeClass('active');
        $this_i.addClass('active');

        // 隐藏其他动态行
        $table_01.find('tr.zy-dy-tr').hide();

        // 有则显示 无则填充
        if ($dy_tr.length > 0) {
            $dy_tr.show();
        } else {
            showRepairDetails($tr, defectId, status, data_code, $this_i, data_pipe);
        }
    });

    // 维修记录步骤 - 数字圆圈
    $table_01.delegate('i.zy-num-click', 'click', function () {
        var $this_i = $(this);
        if (!($this_i.hasClass('gray'))) {
            $table_01.find('i.zy-num-click').removeClass('active');
            $this_i.addClass('active');
            var data_node = $this_i.attr('data-node');
            var data_id = $this_i.attr('data-id');
            $table_01.find('tr[data-defectid-repair="' + data_id + '"]').find('div.zy-dy-info').empty().append(recordContent[data_node]);
        }
    });

    // 填充维修记录
    function showRepairDetails(tr, id, status, code, tag, pipe) {

        // 如果是流程完成状态,直接跳转到作业点页面
        if (status === 'ALREADY_REPAIR' || status === 'DIFFICULT_TO_REPAIR' || status === 'WAIT_FOR_REPLACE') {
            var project_name = $project_name.text();
            var url = DyyBase.root_path + '/pbf/defectRepairMgr/repairWorkRecord.html?id=' + id + '&name=' + DyyBase.unicodeUrl(project_name) + '&code=' + code + '&pipe=' + DyyBase.unicodeUrl(pipe);
            window.location.href = url;
        }

        DyyBase.ajax(defectApi.url_repair_record_all(), {defectId: id}, function (dataset) {
            if (dataset.bool) {
                recordContent.head = '';
                recordContent.body = '';
                loopNode(dataset.result, id, code, tr, status, tag);
                //loopNode(alldata, id, code, tr, status, tag);
            }
        })
    }

    // 显示地图
    function showMapOrList(btn, tag) {
        $('span.zy-map-span').removeClass('active');
        btn.addClass('active');
        if (tag === 'list') {
            $('#JQ_blk_01').show();
            $('#JQ_blk_02').height(0);
        } else if (tag === 'map') {
            $('#JQ_blk_01').hide();
            $('#JQ_blk_02').height(600);

            var pipeGisId = $('#JQ_pipeGisId').val();
            gisJsonArr[0].gisIdArray.push(pipeGisId);

            var $gisid = $('input[name="gisid"]');
            $gisid.each(function () {
                var $this = $(this);
                if ($this.val() != '-') {
                    gisJsonArr[1].gisIdArray.push($this.val());
                }
            });

            if (dyMap || curent_map) {
                dyMap(curent_map, gisJsonArr);
            } else {
                dyMapIfarme.attr('src', '/gis/default/webmap/baseMapDefectRepair.jsp');
                dyMapIfarme.get(0).onload = function () {
                    dyMap = this.contentWindow.queryMutiLayers;
                    curent_map = this.contentWindow.basePipeMap.currentMap;
                    dyMap(curent_map, gisJsonArr);
                };
            }
        }
    }

    // 切换GIS地图
    $('#JQ_toggle_list').click(function () {
        showMapOrList($(this), 'list');
    });
    $('#JQ_toggle_gis').click(function () {
        showMapOrList($(this), 'map');
    });


    // 返回列表
    $('#JQ_goback_repair_list').click(function () {
        window.location.href = DyyBase.root_path + '/pbf/RepairTask/init.html';
    });

})(jQuery, window, document);
